<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的购物车</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css"/>

    <script src="js/vue.js"></script>
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background-color: #EEEEEE;
        }

        .navbar-text a {
            color: #ffffff;
        }

        .login-text {
            margin-right: 50px;
        }

        .logo {
            color: #E94F4C;
            font-size: 35px;
            display: inline-block;
        }

        .search-box {
            height: 48px;
        }

        .input-group-addon {
            background-color: #E94F4C;
            border: none;
            color: #ffffff;
        }

        .control-icon {
            position: absolute;
            top: 50%;
        }

        .mgt38 {
            margin-top: 30px;
        }

        .thumbnail a img {
            height: 200px;
            width: 200px;
        }

        .thumbnail .description {
            height: 40px;
            overflow: hidden;
        }

        a:hover {
            text-decoration: none;
        }

        h3, p {
            text-align: center;
        }

        table tr {
            background-color: #ffffff;
        }

        .dropdown {
            margin: 8px;
            float: right;
            display: none;
        }

        #dropdownMenu1 {
            border: none;
            background-color: #222;
            color: #FFFFFF;
        }

        .dropdown-menu {
            text-align: center;
        }

        .dropdown-menu > li > a > i {
            float: left;
            margin-left: 10px;
        }

        .login {
            display: block;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-default navbar-inverse navbar-static-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <a href="shop_show.html" class="navbar-brand" style="color: #ffffff;"><i class="fa fa-space-shuttle"></i>火箭速购</a>
        </div>
        <div class="navbar-right" id="login">
            <p class="navbar-text">
                <a href="login.jsp">登录</a>
            </p>
            <p class="navbar-text">
                <a href="register.html">注册</a>
            </p>
        </div>
        <div class="dropdown" id="dropdown">
            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown"
                    aria-haspopup="true" aria-expanded="true">
                欢迎你，<span>{{username}}</span>
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                <li><a href="shop-cart.html"><i class="fa fa-shopping-cart"></i>我的购物车</a></li>
                <li><a href="order.html"><i class="fa fa-shopping-basket"></i>我的订单</a></li>
                <li><a href="login.jsp" onclick="quit()"><i class="fa fa-exchange"></i>切换账号</a></li>
                <li><a href="javascript:void(0)" onclick="quit()"><i class="fa fa-sign-out"></i>退出登录</a></li>
            </ul>
        </div>
    </div>
</nav>
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <table id="app" class="table">
                <thead>
                <tr>
                    <td>商品</td>
                    <td>单价</td>
                    <td>数量</td>
                    <td>小计</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody>
                <tr v-for="g in goods">
                    <td style="max-width: 200px;">
                        <div class="media">
                            <div class="media-left">
                                <a href="javascript: void(0);">
                                    <img class="media-object" height="80px" width="62px" :src="g.smallPic">
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">{{g.title}}</h4>
                            </div>
                        </div>
                    </td>
                    <td>{{g.price}}</td>
                    <td>
                        <div class="input-group" style="width: 120px;">
                            <!-- v-if 如果成立就显示该dom元素 -->
                            <span v-if="g.num == 1" style="background-color: #e2e2e2;"
                                  class="input-group-addon">-</span>
                            <!-- v-else必须和v-if放在一起 -->
                            <span :gid="g.goodId" onclick="reduceGoodNum(this)" v-else class="input-group-addon"
                                  style="cursor: pointer;">-</span>
                            <input class="form-control" v-model="g.num">
                            <span :gid="g.goodId" class="input-group-addon" onclick="addGoodNum(this)"
                                  style="cursor: pointer;">+</span>
                        </div>
                    </td>
                    <td>{{g.price * g.num}}</td>
                    <td>
                        <button :id="g.goodId" onclick="deleteSpecifyGood(this)" class="btn btn-default">删除</button>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr v-if="goods.length != 0">
                    <td colspan="5">
                        已选购 <span id="totalCount" style="color: red;">{{totalNum}}</span> 件商品,
                        总价 <span style="color: red;" id="totalPrice">{{totalPrice}}</span>
                        <button onclick="gotoSettleCount()" class="btn btn-danger btn-lg">去结算</button>
                    </td>
                </tr>
                <tr v-else>
                    <td colspan="5">暂无商品.<a href="shop_show.html">去购物</a></td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
</body>
<script>

    var vm = new Vue({
        el: '#app',
        data: {
            goods: [],
            totalNum: 0,
            totalPrice: 0
        },
        code: 0
    });

    var vm2 = new Vue({
        el: '#dropdown',
        data: {
            username: null
        },
    });

    //登录验证
    $(function () {
        $.ajax({
            url: 'login',
            type: 'get',
            dataType: 'json',
            data: {
                method: "login"
            },
            success: function (_data) {
                console.log(_data);
                // 如果用户登录
                code = _data.code;
                vm2.username = _data.username;
                if (code == 2) {
                    $('#login').css('display', 'none');
                    $('#dropdown').css('display', 'block')
                }
            }
        })
    });

    //退出登录
    function quit() {
        $.ajax({
            url: 'login',
            type: 'get',
            dataType: 'json',
            data: {method: "quit"}
        });
        localStorage.removeItem('local_shopping_cart');
        location.reload();
    }

    //购物车数据初始化
    var localShoppingCart = localStorage.getItem('local_shopping_cart');

    //判断本地购物车是否有数据
    if (localShoppingCart) {
        //本地数据转换为json数据
        localShoppingCart = JSON.parse(localShoppingCart);
        //取得商品id的数组
        var goodIds = Object.keys(localShoppingCart);
        console.log(localShoppingCart);
        // join(‘,’) 只用指定的字符将数组拼接成字符串
        var goodIdsStr = goodIds.join(','); // ['1001', '1002', '1003'] -> 1001,1002,1003
        //用商品id获取商品信息
        $.ajax({
            url: 'good/ids',
            type: 'post',
            dataType: 'json',
            data: {ids: goodIdsStr},
            success: function (_data) {  // [{}, {}, {}]
                var totalNum = 0;  //总数量
                var totalPrice = 0;//总价格
                for (var i = 0; i < _data.length; i++) {
                    var good = _data[i];  //获取到每件商品
                    var goodId = good.goodId; //获取商品的id, 目的是获取商品的数量
                    // 动态的添加的属性, 购买的商品数量
                    good.num = localShoppingCart['' + goodId];

                    totalNum += good.num;   //计算总数量
                    totalPrice += (good.num * good.price); //计算总的价格
                    vm.goods.push(good);
                }
                vm.totalNum = totalNum;
                vm.totalPrice = totalPrice;
            }
        })
    }

    //购物车商品的数量减1
    function reduceGoodNum(reduceTag) {
        //获取id
        var goodId = $(reduceTag).attr('gid');
        //获取本地购物车所有的商品数据
        var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
        //获取指定id的商品的数量，并--
        var num = --localShoppingCart[goodId];
        //给对应的商品的数量重新赋值
        localShoppingCart[goodId] = num;
        // 改变商品的数量：1.登录；2.未登录
        changeChartNum(goodId, num, localShoppingCart);
    }

    //购物车商品的数量加1
    function addGoodNum(addTag) {
        //获取id
        var goodId = $(addTag).attr('gid');  //goodId 是String类型
        // 获取本地购物车的数据
        var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
        //获取指定id的商品的数量，并++
        var num = ++localShoppingCart[goodId];
        //给对应的商品的数量重新赋值
        localShoppingCart[goodId] = num;
        // 改变商品的数量：1.登录；2.未登录
        changeChartNum(goodId, num, localShoppingCart);
    }

    // 改变购物车对应的商品的数量， 分为远程和本地
    function changeChartNum(goodId, num, lsc) {
        // 表示用户登录了, 需要去同步远程服务器端的数据
        if (code == 2) {
            $.ajax({
                url: 'cart/updGood',
                type: 'post',
                dataType: 'json',
                data: {goodId: goodId, num: num},
            })
            localStorage.setItem('local_shopping_cart', JSON.stringify(lsc));
            reRenderCart(goodId, num)
        } else {  // 如果用户没有登录，只用同步本地就行了
            localStorage.setItem('local_shopping_cart', JSON.stringify(lsc));
            reRenderCart(goodId, num)
        }
    }

    //加、减后渲染购物车数据
    function reRenderCart(goodId, num) {
        //取出所有的商品
        var goodList = vm.goods;
        //字符串转数字
        goodId = Number(goodId);
        //定义商品的总数量和总价格
        var totalNum = 0;  //总数量
        var totalPrice = 0;//总价格
        //遍历vue里的所有商品
        for (var i = 0; i < goodList.length; i++) {
            var good = goodList[i];
            //修改对应的商品数量
            if (good.goodId == goodId) {
                good.num = num;
            }
            totalNum += good.num;
            totalPrice += (good.num * good.price);
        }
        //本地总数变化
        vm.totalNum = totalNum;
        vm.totalPrice = totalPrice;
    }


    // 删除购物车中指定的商品
    function deleteSpecifyGood(delbtnTag) {
        //获取商品ID
        var goodId = $(delbtnTag).prop('id');
        //字符串转json
        var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
        // 如果用户登录, 需要删除服务器端购物车中对应的商品
        if (code == 2) {
            removeServerCartData(goodId);
        }
        //删除本地对应的商品
        delete localShoppingCart[goodId];

        var totalNum = 0;  // 商品的总数量
        var totalPrice = 0;  // 总价格

        //表示清空了
        if (Object.keys(localShoppingCart).length == 0) {
            // 将存储购物车的信息删掉
            localStorage.removeItem('local_shopping_cart');
            vm.totalNum = 0;
            vm.totalPrice = 0;
            vm.goods = [];
            return;
        }
        //更新本地购物车数据
        localStorage.setItem('local_shopping_cart', JSON.stringify(localShoppingCart));

        var goodList = vm.goods;  //取出所有的商品
        goodId = Number(goodId); // 将字符串转换为数字类型
        //遍历本地所有商品
        for (var i = 0; i < goodList.length; i++) {
            var good = goodList[i];
            if (goodId == good.goodId) {
                goodList.splice(i, 1);  // 删除指定的商品
                i--;
            } else {  //没有删除的商品要纳入计算
                totalNum += good.num;
                totalPrice += (good.num * good.price);
            }
        }
        vm.totalNum = totalNum;
        vm.totalPrice = totalPrice;
    }

    // 删除掉远程服务器端对应的购物车数据
    function removeServerCartData(goodId) {
        $.ajax({
            url: 'cart/delGood',
            type: 'post',
            dataType: 'json',
            data: {goodId: goodId}
        })
    }

    // 点击 "结算" 按钮，到达结算页面
    function gotoSettleCount() {
        //验证登陆
        $.ajax({
            url:'login',
            data:{method:'login'},
            type:'get',
            datatype:'json',
            success:function (_data) {
                if (_data.code==2) {
                    window.location.href = "shop_end.html"
                }else if (_data.code==1) {
                    window.location.href = "login.jsp"
                }

            }
        })

    }

    // 显示错误提示信息
    function showErrorBox(msgText) {
        Lobibox.notify('warning', {
            size: 'mini',
            delay: 2000,
            delayIndicator: false,
            title: false, //不给title
            msg: msgText,
            sound: false  // 不要音频
        })
    }
</script>
</html>